<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="标签内容" prop="name">
        <el-input v-model.trim="formData.name" placeholder="请输入标签内容" />
      </el-form-item>
      <el-form-item label="标签颜色" prop="bgColor">
        <div class="flex items-center">
          <div :class="['colorDiv',{colorCurrent: item == formData.bgColor}] " v-for="item,index in defaultColors.slice(2)" :key="index+'color'">
            <span @click="chooseBgColor(item)" :style="{background: item}" class="colorSpan box-border inline-block h-22px h-full w-22px cursor-pointer b-1 b-#909399 p-4px"></span>
          </div>
        </div>
        <el-color-picker show-alpha  @change="bgPickerChange" />
      </el-form-item>
      <el-form-item label="文字颜色" prop="textColor">
        <div class="flex items-center">
          <div :class="['colorDiv',{colorCurrent: item == formData.textColor}] " v-for="item,index in [defaultColors[1],defaultColors[0],...[...[...defaultColors].slice(2,6),...[...defaultColors].slice(8)].reverse()]" :key="index+'color'">
            <span @click="chooseTextColor(item)" :style="{background: item}" class="colorSpan box-border inline-block h-22px h-full w-22px cursor-pointer b-1 b-#909399 p-4px"></span>
          </div>
        </div>
        <el-color-picker show-alpha  @change="textPickerChange" />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number
          style="width: 200px"
          :min="1"
          :max="100"
          :step="1"
          v-model="formData.sort"
          placeholder="请输入排序"
        />
      </el-form-item>
      <el-form-item label="预览">
        <EntTag
          :content="formData.name"
          :bgColor="formData.bgColor"
          :textColor="formData.textColor"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button
        @click="delForm"
        type="danger"
        v-hasPermi="['crm:label:delete']"
        style="float: left"
        v-if="formType == 'update'"
        >删 除</el-button
      >
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as customerTagApi from '@/api/crm/customerTagConfig/index'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  setId: undefined,
  name: undefined,
  bgColor: 'rgba(2, 129, 252, 1)',
  textColor: '#ffffff',
  sort: undefined,
  id: undefined
})
const formRules = reactive({
  name: [{ required: true, message: '标签内容不能为空', trigger: 'blur' }],
  bgColor: [{ required: true, message: '标签颜色不能为空', trigger: 'blur' }],
  textColor: [{ required: true, message: '文字颜色不能为空', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref
const defaultColors = ref([
  '#000000',
  '#ffffff',
  'rgba(2, 129, 252, 1)',
  'rgba(43, 151, 255, 1)',
  'rgba(80, 168, 252, 1)',
  'rgba(124, 190, 252, 1)',
  'rgba(255, 0, 0, 1)',
  'rgba(252, 50, 50, 1)',
  'rgba(255, 98, 98, 1)',
  'rgba(252, 143, 143, 1)',
  'rgba(255, 208, 0, 1)',
  'rgba(252, 214, 45, 1)',
  'rgba(254, 225, 97, 1)',
  'rgba(251, 232, 147, 1)',
])

const chooseBgColor = (color)=>{
  formData.value.bgColor = color
}
const chooseTextColor = (color)=>{
  formData.value.textColor = color
}
const bgPickerChange = (color)=>{
  formData.value.bgColor = color
}
const textPickerChange = (color)=>{
  formData.value.textColor = color
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  if (type == 'create') formData.value.setId = id
  if (type == 'update') {
    formData.value = await customerTagApi.getTaglabel(id)
  }
  formLoading.value = false
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await customerTagApi.createlabel(data)
      message.success(t('common.createSuccess'))
    }
    if (formType.value === 'update') {
      await customerTagApi.updatelabel(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    setId: undefined,
    name: undefined,
    bgColor: 'rgba(2, 129, 252, 1)',
    textColor: '#ffffff',
    sort: undefined,
    id: undefined
  }
  formRef.value?.resetFields()
}
/*删除*/
const delForm = () => {
  ElMessageBox.confirm('确定要删除当前标签吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const res = await customerTagApi.deleteTag(formData.value.id)
      dialogVisible.value = false
      if (res) ElMessage.success('删除成功!')
      emit('success')
    })
    .catch(() => {})
}
</script>

<style scoped lang="scss">
.colorDiv{
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 4px;
  border: 1px solid #fff;
  border-radius: 4px;
}
.colorSpan {
  border: 1px solid var(--el-text-color-secondary);
}
.colorCurrent {
  border: 1px solid var(--el-text-color-secondary);
}
::v-deep(.el-color-picker__trigger:hover)  {
  border-color: #fff;
}
::v-deep(.el-color-picker__trigger) {
  border-color: #fff;

}
</style>